<template>
  <div class="app-container">

    <div class="filter-container">
      <el-input v-model="studentQuery.sno" placeholder="学号" clearable style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-input v-model="studentQuery.name" placeholder="姓名" clearable style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-select v-model="studentQuery.gender" placeholder="请选择性别" clearable style="width: 200px" class="filter-item" @keyup.enter.native="handleFilter">
        <el-option v-for="item in genderOptions" :key="item.key" :label="item.label" :value="item.key" />
      </el-select>
      <el-input v-model="studentQuery.phone" placeholder="手机号" clearable style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-select v-model="studentQuery.department" placeholder="请选择院系" clearable style="width: 200px" class="filter-item" @keyup.enter.native="handleFilter">
        <el-option v-for="item in departmentOptions" :key="item.id" :label="item.name" :value="item.id" />
      </el-select>
      <el-select v-model="studentQuery.major" placeholder="请选择专业" clearable style="width: 200px" class="filter-item" @keyup.enter.native="handleFilter">
        <el-option v-for="item in majorOptions" :key="item.id" :label="item.name" :value="item.id" />
      </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加
      </el-button>
      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        导出
      </el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column label="学号" width="200">
        <template slot-scope="scope">
          {{ scope.row.sno }}
        </template>
      </el-table-column>
      <el-table-column label="姓名" width="200" align="center">
        <template slot-scope="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column label="性别" width="200" align="center">
        <template slot-scope="scope">
          {{ scope.row.gender }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="手机号" width="200">
        <template slot-scope="scope">
          {{ scope.row.phone }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="院系" width="200">
        <template slot-scope="scope">
          {{ scope.row.department }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="专业" width="200">
        <template slot-scope="scope">
          {{ scope.row.major }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="medium" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button size="medium" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="page" :limit.sync="limit" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
      <el-form ref="dataForm" :rules="rules" :model="student" label-position="left" label-width="100px" style="width: 400px; margin-left:50px;">
        <el-form-item label="学号" prop="sno">
          <el-input v-model="student.sno" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="student.name" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="student.gender" placeholder="请选择性别" clearable style="width: 300px;">
            <el-option v-for="item in genderOptions" :key="item.key" :label="item.label" :value="item.key" />
          </el-select>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="student.phone" />
        </el-form-item>
        <el-form-item label="院系" prop="department">
          <el-select v-model="student.department" placeholder="请选择院系" clearable style="width: 300px;" @change="departmentChange()">
            <el-option v-for="item in departmentOptions" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="专业" prop="major">
          <el-select v-model="student.major" placeholder="请选择专业" clearable :disabled="majorDisabled" style="width: 300px;">
            <el-option v-for="item in majorOptions" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { getList, remove, save, update, getStudent, departmentList, majorList, majorListById } from '@/api/student'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

export default {
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      list: null,
      listLoading: true,
      total: 0,
      page: 1,
      limit: 10,
      studentQuery: {
        sno: '',
        name: '',
        gender: '',
        phone: '',
        department: '',
        major: ''
      },
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '添加'
      },
      student: {
        id: '',
        sno: '',
        name: '',
        gender: '',
        phone: '',
        department: '',
        major: ''
      },
      dialogFormVisible: false,
      rules: {
        sno: [{ required: true, message: '学号不能为空', trigger: 'blur' }],
        name: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
        gender: [{ required: true, message: '性别不能为空', trigger: 'blur' }],
        phone: [{ required: true, message: '手机号不能为空', trigger: 'blur' }],
        department: [{ required: true, message: '院系不能为空', trigger: 'blur' }],
        major: [{ required: true, message: '专业不能为空', trigger: 'blur' }]
      },
      downloadLoading: false,
      genderOptions: [{ label: '男', key: 1 }, { label: '女', key: 0 }],
      departmentOptions: [],
      majorDisabled: true,
      majorOptions: []
    }
  },
  created() {
    this.getList()
    departmentList().then((response) => {
      this.departmentOptions = response.data
    })
    majorList().then((response) => {
      this.majorOptions = response.data
    })
  },
  methods: {
    getList() {
      this.listLoading = true
      getList(this.page, this.limit, this.studentQuery).then(response => {
        this.list = response.data.records
        this.total = response.data.total
        this.listLoading = false
      })
    },
    handleFilter() {
      this.page = 1
      this.getList()
    },
    departmentChange() {
      this.majorOptions = []
      this.student.major = ''
      if (this.student.department !== '') {
        majorListById(this.student.department).then(response => {
          this.majorOptions = response.data
          this.majorDisabled = false
        })
      }
    },
    handleCreate() {
      this.resetStudent()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    resetStudent() {
      this.student = {
        id: '',
        sno: '',
        name: '',
        gender: '',
        phone: '',
        department: '',
        major: ''
      }
      this.majorDisabled = true
      this.majorOptions = []
    },
    // 添加或编辑后回显到表格的数据需要处理
    setDepartment(data) {
      this.departmentOptions.find((item) => {
        if (item.id === data.department) {
          data.department = item.name
          return
        }
      })
      this.majorOptions.find((item) => {
        if (item.id === data.major) {
          data.major = item.name
          return
        }
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          save(this.student).then((response) => {
            this.dialogFormVisible = false
            this.setDepartment(response.data)
            this.list.unshift(response.data)
            this.$notify({
              title: 'Success',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    async handleUpdate(row) {
      // 获取学生信息
      const res = await getStudent(row.id)
      this.student = res.data
      // 根据学生信息获取院系和专业
      const majorList = await majorListById(this.student.department)
      this.majorDisabled = false
      this.majorOptions = majorList.data
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          update(this.student).then((response) => {
            this.dialogFormVisible = false
            this.setDepartment(response.data)
            const index = this.list.findIndex(v => v.id === response.data.id)
            this.list.splice(index, 1, response.data)
            this.$notify({
              title: 'Success',
              message: '修改成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row, index) {
      this.$notify({
        title: 'Success',
        message: '删除成功',
        type: 'success',
        duration: 2000
      })
      this.list.splice(index, 1)
      remove(row.id)
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['学号', '姓名', '性别', '手机号', '院系', '专业']
        const filterVal = ['sno', 'name', 'gender', 'phone', 'department', 'major']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '学生信息'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    }
  }
}
</script>
